#!/usr/bin/env python

"""
Try to run Frescobaldi immediately without installing.
Does not require CMake and make for release tar balls.
Checks the python version and modules.
If not Python 2.6 try to rerun ourselves with python 2.6.
Creates a local installdir (inside the frescobaldi-x.x.x directory).
Creates a menu in the local xdgdata-apps dir.
Records the current Okular textedit binding.
Adjusts some settings and directly runs Frescobaldi.
After having run this, users can run './frescobaldi' directly.
Calling python run or ./run again will display a dialog with options
to remove the Applications menu entry and restore the Okular binding.
"""

import glob, itertools, os, re, subprocess, sys

def findAllExe(command):
    """Returns an iterable over all occurences of the command in the PATH."""
    for p in os.environ.get("PATH", os.defpath).split(os.pathsep):
        path = os.path.join(p, command)
        if os.access(path, os.X_OK):
            yield path

def findExe(command):
    """Returns the first found command in the PATH or None if not found."""
    for path in findAllExe(command):
        return path

def die(msg):
    """Show a message and exit with exitcode 1."""
    try:
        KMessageBox.error(None, msg)
    except Exception:
        if os.environ.get('DISPLAY') and findExe('kdialog'):
            subprocess.call(['kdialog', '--error', msg])
        else:
            sys.stderr.write(msg+'\n')
    sys.exit(1)

def configure_file(infile, outfile, dictionary):
    """Replace variables in infile and write the result to outfile.
    
    Variables consist of uppercase letters and may contain underscores.
    They start and end with the ampersand character. E.g. @MODULE_DIR@.
    This is analogous to the CMake configure_file function.
    
    Raises KeyError if a variable does not exist in the dictionary.
    
    """
    with open(outfile, 'w') as f:
        f.write(re.sub(r'@([A-Z]+(_[A-Z]+)*)@',
            lambda m: dictionary[m.group(1)], open(infile).read()))

def makedirs(path, mode=0o777):
    """Like os.makedirs(), but doesn't error out if the full path exists."""
    if not os.path.exists(path):
        os.makedirs(path)

# html
p = lambda s: '<p>%s</p>\n' % s
li = lambda s: '<li>%s</li>\n' % s
ul = lambda *args: '<ul>\n%s</ul>\n' % ''.join(args)

# this should return true if the Python version (supplied in tuple) can be used.
usableVersion = lambda version: (2, 6) <= version < (3, 0)

# Check version of current running Python
if not usableVersion(sys.version_info[:2]):
    # find another one that can be used
    for path in itertools.chain(
            findAllExe('python'),
            findAllExe('python2.6'),
            findAllExe('python2.7'),
            findAllExe('python2'),
            findAllExe('python26'),
            findAllExe('python27'),
    ):
        # Get the output of 'python --version'
        ver = subprocess.Popen(
            [path, "--version"], stderr=subprocess.PIPE).communicate()[1]
        # Convert to a tuple of ints like (2, 6, 5)
        ver = tuple(map(int, re.findall(r'\d+', ver)))
        if usableVersion(ver):
            os.execl(path, path, sys.argv[0])
    die("Could not find Python 2 version 2.6 or above.\n\n"
        "Please install the 2.6 or 2.7 version of Python.")

# find out our directory
curdir = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(curdir)
sys.path.insert(0, curdir)

try:
    import sip
    sip.setapi("QString", 2)
    sip.setapi("QVariant", 2)
except Exception:
    die("Please install the Python-SIP module.\nCan't set the sip API.")

# check modules
import checkmodules
missing = checkmodules.checkModules()
if missing:
    die("The following Python modules are missing: %s.\n\n"
        "Please install them and try again." % ", ".join(missing))

# check versions
versions = checkmodules.checkVersions()
if versions:
    die("Some packages have outdated versions:\n\n" + "\n".join(versions))

# Everything look OK!

# brutally use some modules from Frescobaldi
sys.path[0] = os.path.join(curdir, 'python')

# Construct KApplication

import shutil

from PyKDE4.kdecore import (
    KAboutData, KCmdLineArgs, KConfig, KGlobal, ki18n, KPluginLoader)
from PyKDE4.kdeui import (
    KApplication, KDialog, KGuiItem, KMessageBox, KStandardGuiItem)
from PyKDE4.kio import KUrlRequesterDialog

aboutData = KAboutData(
    'frescobaldi_runner',       # appName
    'frescobaldi_runner',       # catalogName
    ki18n('Frescobaldi Runner'),# programName
    '1.0'                       # version
    )

KCmdLineArgs.init(sys.argv, aboutData)
app = KApplication()

# set some directories/values
data = {}

m = re.search(r'set\(VERSION\s+"(.*?)"', open('CMakeLists.txt').read())
if not m:
    die("Internal error: could not determine version from CMakeLists.txt")

data['VERSION'] = m.group(1)
data['MODULE_DIR'] = os.path.join(curdir, "python")
data['PYTHON_EXECUTABLE'] = sys.executable
data['CMAKE_INSTALL_PREFIX'] = os.path.join(curdir, 'image')
data['APP_DIR'] = os.path.join(
    data['CMAKE_INSTALL_PREFIX'], 'share', 'apps', 'frescobaldi')


icon_install_dir = KGlobal.dirs().saveLocation('icon', 'hicolor/scalable/apps/')
html_install_dir = KGlobal.dirs().saveLocation('html', 'en/')
xdgdata_apps_install_dir = KGlobal.dirs().saveLocation('xdgdata-apps')
locale_install_dir = os.path.join(
    data['CMAKE_INSTALL_PREFIX'], 'share', 'locale')

# some shortcuts
app_dir = data['APP_DIR']
desktop_file = os.path.join(xdgdata_apps_install_dir, 'frescobaldi.desktop')


class TarBall:
    """Used when running from a Frescobaldi release tar ball.
    
    Does not need CMake and make.
    
    """
    
    builddir = 'prebuilt'
    
    def makeImage(self):
        # puts some files under image/share/ ...
        makedirs(app_dir)
        
        # default config file
        config_dir = os.path.join(data['CMAKE_INSTALL_PREFIX'], 'share', 'config')
        makedirs(config_dir)
        shutil.copy(os.path.join(curdir, 'data', 'frescobaldirc'), config_dir)
        
        # data files
        for name in (
                'frescobaldiui.rc',
                'expansions',
                'frescobaldi.notifyrc',
        ):
            dest = os.path.join(app_dir, name)
            if os.path.exists(dest):
                os.remove(dest)
            os.symlink(os.path.join(curdir, 'data', name), dest)
        
        # data directories
        for name in ('rumor', 'icons', 'css'):
            dest = os.path.join(app_dir, name)
            if os.path.exists(dest):
                os.remove(dest)
            os.symlink(os.path.join(curdir, name), dest)
        
        # pics
        dest = os.path.join(app_dir, 'pics')
        if os.path.exists(dest):
            os.remove(dest)
        os.symlink(os.path.join(curdir, self.builddir, 'pics'), dest)
        
        # install mo files
        for mo in glob.glob(os.path.join(self.builddir, 'po', '*.mo')):
            lang = os.path.splitext(os.path.basename(mo))[0]
            langdir = os.path.join(locale_install_dir, lang, 'LC_MESSAGES')
            makedirs(langdir)
            shutil.copy(mo, os.path.join(langdir, 'frescobaldi.mo'))
        
    def installBinary(self):
        # create the frescobaldi 'binary'
        configure_file('frescobaldi.py', 'frescobaldi', data)
        os.chmod('frescobaldi', 0o744)
    
    def installFrescobaldi(self):
        # create the frescobaldi 'binary'
        self.installBinary()
        
        # put appIcon in icondir
        shutil.copy(
            os.path.join('data', 'frescobaldi-lily.svg'),
            os.path.join(icon_install_dir, 'frescobaldi.svg'))
        
        # install desktop file
        desktop = open(os.path.join('data', 'frescobaldi.desktop')).read()
        newdesktop = re.sub(r'\bExec=frescobaldi\b',
            'Exec=%s/frescobaldi' % curdir, desktop)
        with open(desktop_file, 'w') as f:
            f.write(newdesktop)

        # install link to documentation
        os.symlink(os.path.join(curdir, 'doc'),
            os.path.join(html_install_dir, 'frescobaldi'))
        

class SVN(TarBall):
    """Used when running from a Frescobaldi SVN checkout.
    
    Needs CMake and make, lilypond and msgfmt.
    
    """
    
    builddir = 'build'
    
    def makeImage(self):
        # run CMake
        # check some programs.
        missing = []
        if not findExe('cmake'):
            missing.append(
                "CMake is needed to run Frescobaldi from a SVN checkout.\n"
                "Please install CMake.")
        if not findExe('make'):
            missing.append(
                "Make is needed to run Frescobaldi from a SVN checkout.\n"
                "Please install a 'make' program.")
        if not findExe('convert'):
            missing.append(
                "'convert' (from ImageMagick) is needed to run Frescobaldi "
                "from a SVN checkout.\nPlease install ImageMagick.")
        if not findExe('msgfmt'):
            missing.append(
                "'msgfmt' (from Gettext) is needed to run Frescobaldi "
                "from a SVN checkout.\nPlease install Gettext.")
        if missing:
            die('\n\n'.join(missing))
        
        import ly.version
        for lily in findAllExe('lilypond'):
            if ly.version.LilyPondInstance(lily).version() >= (2, 13, 21):
                break
        else:
            config = KGlobal.config().group(None)
            lily = config.readEntry("lilypond", "lilypond")
            dlg = KUrlRequesterDialog(lily, 
                "LilyPond >= 2.13.21 is needed to run Frescobaldi from a SVN "
                "checkout.\n\nPlease install a recent LilyPond (e.g. from a "
                "binary download) and select the binary here.", None)
            if dlg.exec_():
                lily = dlg.selectedUrl().path()
                config.writeEntry("lilypond", lily)
                config.sync()
            else:
                sys.exit(1)
                
        makedirs(self.builddir)
        if subprocess.call([
            'cmake', '..',
            '-DCMAKE_INSTALL_PREFIX=' + data['CMAKE_INSTALL_PREFIX'],
            '-DPYTHON_EXECUTABLE=' + sys.executable,
            '-DLILYPOND_EXECUTABLE=' + lily,
            '-DBYTECOMPILE=NO',
            ], cwd=self.builddir):
            die("CMake exited with an error.")
        if subprocess.call(['make'], cwd=self.builddir):
            die("Make exited with an error.")
        if subprocess.call(['make', 'install'], cwd=self.builddir):
            die("'make install' exited with an error.")
            
    def installBinary(self):
        shutil.copy2(os.path.join(self.builddir, 'frescobaldi'), 'frescobaldi')
        os.chmod('frescobaldi', 0o744)


def removeFrescobaldi():
    # remove the frescobaldi 'binary'
    os.remove('frescobaldi')
    
    # remove appIcon
    os.remove(os.path.join(icon_install_dir, 'frescobaldi.svg'))
    
    # remove desktop file
    os.remove(desktop_file)
    
    # remove link to documentation
    os.remove(os.path.join(html_install_dir, 'frescobaldi'))

def runFrescobaldi():
    subprocess.Popen([os.path.join(curdir, 'frescobaldi')],
        cwd=os.environ.get('HOME'))

def saveOkularPart():
    """Save the current OkularPart editor settings."""
    okularpartrc = KConfig("okularpartrc", KConfig.NoGlobals)
    group = okularpartrc.group("General")
    
    ourconfig = KGlobal.config()
    ourgroup = ourconfig.group('okular editor')
    
    ourgroup.writeEntry("ExternalEditor",
        group.readEntry("ExternalEditor", ""))
    ourgroup.writeEntry("ExternalEditorCommand",
        group.readEntry("ExternalEditorCommand", ""))
    ourconfig.sync()

def configureOkularPart():
    """Lets Frescobaldi configure itself as custom editor in Okular."""
    config = KConfig("frescobaldirc", KConfig.NoGlobals)
    group = config.group("")
    group.writeEntry("configure okularpart", True)
    group.sync()

def restoreOkularPart():
    """Restore the saved OkularPart editor settings."""
    okularpartrc = KConfig("okularpartrc", KConfig.NoGlobals)
    group = okularpartrc.group("General")
    
    ourconfig = KGlobal.config()
    ourgroup = ourconfig.group('okular editor')
    
    group.writeEntry("ExternalEditor",
        ourgroup.readEntry("ExternalEditor", ""))
    group.writeEntry("ExternalEditorCommand",
        ourgroup.readEntry("ExternalEditorCommand", ""))
    group.sync()

def main():
    # if the desktop file and the 'binary' do exist,
    # assume Frescobaldi is installed and can be run.
    if os.path.exists(desktop_file) and os.path.exists('frescobaldi'):
        # Frescobaldi can be run. Offer options to remove or run Frescobaldi
        result = KMessageBox.questionYesNoCancel(None, '<qt>' +
                p("Frescobaldi is available in your Applications menu.") +
                p("Here you can choose if you want to remove Frescobaldi from "
                  "the menu or to run Frescobaldi.") +
                p("It is recommended that you remove Frescobaldi from the menu "
                  "when you really install Frescobaldi, as that will install a "
                  "system-wide Applications menu entry."),
            None,
            KGuiItem("Run Frescobaldi", 'system-run'),
            KGuiItem("Remove Frescobaldi from menu", 'edit-delete'),
            KStandardGuiItem.cancel())
        if result == KMessageBox.Yes:
            configureOkularPart()
            runFrescobaldi()
        elif result == KMessageBox.No:
            removeFrescobaldi()
            restoreOkularPart()
            configureOkularPart()
            
    else:
        # Frescobaldi seems not to be installed.
        if os.path.exists('prebuilt'):
            installer = TarBall()
        else:
            installer = SVN()
        installer.makeImage()
        installer.installFrescobaldi()
        saveOkularPart()
        configureOkularPart()
        msg = [
            p("Frescobaldi has been added to your Applications menu."),
            p("If you want to remove Frescobaldi from the menu, just run this "
              "'run' script again."),
            p("(It is recommended that you remove Frescobaldi from the menu "
              "when you really install Frescobaldi, as that will install a "
              "system-wide menu Applications menu entry.)"),
            p("Frescobaldi will now be started. Enjoy!")]
        notes = []
        if not findExe('lilypond'):
            notes.append(
                "LilyPond could not be found in your PATH. You really should "
                "install LilyPond to be able to do anything useful with "
                "Frescobaldi! Visit "
                "<a href=\"http://www.lilypond.org/\">www.lilypond.org</a> "
                "for more information.")
        if not KPluginLoader('okularpart').factory():
            notes.append(
                "The Okular PDF viewer KPart module could not be found on your "
                "system. This module provides the PDF preview, so "
                "if the preview doesn't work, you should install Okular.")
        if not KPluginLoader('kmid_part').factory():
            notes.append(
                "The KMid MIDI player KPart module could not be found on your "
                "system. This module is used by the built-in MIDI player. "
                "If the player doesn't work, you should install KMid >= 2.4.0.")
        if not KPluginLoader('libkonsolepart').factory():
            notes.append(
                "The Konsole KPart module could not be found on your system. "
                "This module provides the built-in terminal. If you want to "
                "use the built-in terminal, you should install Konsole.")
        if not findExe('rumor'):
            notes.append(
                "For music input via MIDI, the 'rumor' program is recommended. "
                "See the Frescobaldi User Guide (accessible from Frescobaldi "
                "with the F1 key) for more information.")
        if notes:
            msg[1:1] = p("Note:"), ul(*map(li, notes))
        KMessageBox.information(None, '<qt>' + ''.join(msg), None, None,
            KMessageBox.Options(KMessageBox.Notify | KMessageBox.AllowLink))
        runFrescobaldi()
    return 0
    
if __name__ == "__main__":
    sys.exit(main())
